from wormbane.engine.generate_level import generate_level
from wormbane.engine.save_game import load_level, save_level
from wormbane.engine.actions.dig import action_dig

def command_climb(dir, game):
    feature = game.hero.env.feature
    if feature.is_altar and dir == 'down':
        game.write(game.hero, 'kneels at', feature)
        corpses = [item for item in game.hero.env.items if item.is_corpse]
        for corpse in corpses:
            game.write(corpse, 'is consumed in a flash of light')
            corpse.move_to(None)
        game.hero_moved = True
        return
    elif feature.diggable and game.hero.pick:
        action_dig(game.hero, feature, game)
        game.hero_moved = True
        return
    elif not feature.is_stair or feature.direction != dir:
        game.write(game.hero, 'cannot go %s here' % dir)
        return
    if dir == 'up' and game.level.level_num == 1:
        game.write(game.hero, 'cannot leave the dungeon')
        return

    new_level_num = game.level.level_num + (-1 if dir == 'up' else 1)
    game.hero.move_to(None)
    save_level(game.level)
    try:
        game.level = load_level(new_level_num)
    except IOError:
        game.level = generate_level(new_level_num)
    new_pos = (game.level.stair_down_pos if dir == 'up'
               else game.level.stair_up_pos)
    game.hero.move_to(game.level.cells[new_pos])
    game.hero_moved = True
